package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /*
    * 处理sql异常
    * */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        // ex.message -> 提示异常信息
        // 报错信息：Duplicate entry '王五' for key 'employee.idx_username'
        String message = ex.getMessage();
        // message.contains("Duplicate entry") -> 判断异常信息是否存在 Duplicate entry字段
        if (message.contains("Duplicate entry")){
            // message.split(" "); -> 以空格为标准，分割字符串
            String[] split = message.split(" ");
            String useName = split[2];
            String msg =useName+ "已存在";
            return Result.error(msg);
        }else {
            return Result.error("未知错误");
        }
    }
}
